package com.mission.shaco.warehouse


import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.*
import com.androidquery.AQuery
import com.androidquery.callback.AjaxCallback
import com.androidquery.callback.AjaxStatus
import com.mission.shaco.warehouse.models.ClientConfig
import kotlinx.android.synthetic.main.activity_stock_change.*
import org.json.JSONObject
import android.content.Intent



class StockChangeActivity : ScannerActivity(), RadioGroup.OnCheckedChangeListener {

    var writeToStock = false
    var needReturn = false

    override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
        when(checkedId){

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_stock_change)
        initView()

        var intent = getIntent()
        if(intent != null) {
            val extras = getIntent().extras
            if(extras!=null) {
                val webitemid = extras.getString("webitemid")
                txtSearch.setText(webitemid)
                BasicActivity.setEditTextReadOnly(txtSearch)
                needReturn = true
                txtStock.requestFocus()
                var t = Thread(searchThread)
                t.start()
            }
        }
    }

    var updateThread: Runnable = Runnable {
        try {
            val aq: AQuery = AQuery(this)
            val params = HashMap<String, Any>()

            var map = JSONObject()
            map.put("operator",getOpreateName())
            map.put("sku", txtSearch.getText())
            map.put("stock",txtStock.getText())
            params.put("datas", map)
            var jsonStr = map.toString()

            aq.ajax(ClientConfig.getHostUrl(ClientConfig.JOSN_UPDATE_PRODUCT_STOCK),params, String::class.java,  object : AjaxCallback<String>() {

                override fun callback(url: String, result: String, status: AjaxStatus) {
                    if(status.code == 200){
                        var response: JSONObject = JSONObject(result)
                        if(response.getInt("status") == 1) {
                            noticeMessage("修改成功")
                            if(needReturn){
                                sendResult()
                            }else{
                                txtSearch.requestFocus()
                            }

                        }else{
                            noticeMessage("没找到该产品")
                        }

                        txtSearch.requestFocus()
                    }else{
                        noticeMessage("网络出问题")
                    }
                }
            })

        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
    }


    var searchThread: Runnable = Runnable {
        try {
            val aq: AQuery = AQuery(this)
            val params = HashMap<String, Any>()

            var map = JSONObject()
            map.put("opeater",getOpreateName())
            map.put("sku", txtSearch.getText())
            params.put("datas", map)
             var jsonStr = map.toString()

            aq.ajax(ClientConfig.getHostUrl(ClientConfig.JOSN_GET_PRODUCT_STOCK),params, String::class.java,  object : AjaxCallback<String>() {

                override fun callback(url: String, result: String, status: AjaxStatus) {
                    if(status.code == 200){
                        var response: JSONObject = JSONObject(result)
                        if(response.getInt("status") == 1) {
                            var product = response.getJSONObject("products")
                            txtOldStock.setText(product.getString("position"))
                            txtStock.requestFocus()
                            writeToStock = true
                        }else{
                            noticeMessage("没找到该产品")
                        }
                    }else{
                       noticeMessage("网络出问题")
                    }
                }
            })

        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
    }

    fun initView(){
        btnModifty.setOnClickListener(this)
        btnSearch.setOnClickListener(this)
        btnFinish.setOnClickListener(this)
    }

    fun sendResult(){
        val mIntent = Intent()
        mIntent.putExtra("stock", txtStock.getText())

        this.setResult(android.app.Activity.RESULT_OK,mIntent)
        this.finish()
    }

    override  fun onClick(v: View?) {
        when(v?.id){
            btnModifty.id -> {
                var t  = Thread(updateThread)
                t.start()
            }
            btnSearch.id->{
                var t  = Thread(searchThread)
                t.start()
            }
            btnFinish.id -> {
                finish()
            }
        }
    }

    override fun afterScanReceive() {
        if(!isCurrentClass()) return
        if(!TextUtils.isEmpty(code)) {
            successNotice()

            var text = getFocusText()
            if(text!=null){
                text.setText(code)
            }
            var t = Thread(searchThread)
            t.start()
            code="";
        }
    }

    fun getFocusText(): EditText {
        var bo = txtSearch.hasFocus()
        return if(txtSearch.hasFocus()) txtSearch else txtStock
    }

    /**
     *  配货匹配成功提示
     */
    fun successNotice(){
        player.start()
        vibrator.vibrate(800)
    }

    /**
     *  配货匹配失败提示
     */
    fun failedNotice(){
        vibrator.vibrate(300)
    }



}
